package pers.lance.jmsproject.server;


import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import javax.jms.*;

public class JmsServer {
    ConnectionFactory connectionFactory;
    Connection conn = null;
    Session session;
    String url = "tcp://localhost:61616";
    String queueName = "lance.queue";
    MessageConsumer consumer = null;


    public JmsServer(String url, String queueName) {
        this.url = url;
        this.queueName = queueName;
        ConnectionFactory factory = new ActiveMQConnectionFactory(url);
        try {
            con = factory.createConnection();
            con.start();
            session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }

    }

    public String getMessage() {
        try {
            Destination destination = new ActiveMQQueue(queueName);
            if (consumer == null) consumer = session.createConsumer(destination);
            TextMessage msg = (TextMessage) consumer.receive();
            return msg.getText();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void close() {
        try {
            consumer.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
